package cn.jiemusic.utils;


import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;


@Slf4j
@Component
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucket; // 存储桶名称
    @Value("${minio.endpoint}")
    private String endpoint;

    public String uploadFile(MultipartFile imgFile, String filePath, Long mid) {
        try {
            InputStream inputStream = imgFile.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(mid + "/" + filePath)
                    .stream(inputStream, imgFile.getSize(), -1)
                    .contentType(imgFile.getContentType())
                    .build());

            return endpoint + "/" + bucket + "/" + mid + "/" + filePath;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 上传封面图像的方法
    public void uploadCover(byte[] coverData, String fileName, Long mid) {
        try {
            // 将 byte[] 转换为 InputStream
            InputStream inputStream = new ByteArrayInputStream(coverData);

            // 上传图片到 MinIO
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(mid + "/" + fileName)
                    .stream(inputStream, coverData.length, -1)  // 设置文件大小
                    .contentType("image/jpeg")  // 设置内容类型，根据你的图片格式来设置
                    .build());

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}
